package blt.app_core.http;


import java.io.File;
import java.util.Map;

import blt.app_core.utils.CacheUtil;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * xugaopan on 2016/12/13.
 */
public class DefaultRequestBuilder implements RequestBuilder {
    @Override
    public Request.Builder builderGet(String url, Map<String, String> params) {
        if (url == null) {
            return null;
        }
        StringBuilder sp = new StringBuilder();
        if (params != null) {
            for (Map.Entry<String, String> res : params.entrySet()) {
                String key = res.getKey();
                String value = res.getValue();
                sp.append(key);
                sp.append("=");
                sp.append(value);
                sp.append("&");
            }
        }
        sp.replace(sp.length() - 1, sp.length(), "");
        if (sp.length() != 0) {
            url = url + "?" + sp;
        }
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        builder.get();
        return builder;
    }

    @Override
    public Request.Builder builderPost(String url, Map<String, String> parms) {
        if (url == null) {
            return null;
        }
        Request.Builder builder = new Request.Builder();
        FormBody.Builder formBody = new FormBody.Builder();
        if (parms != null) {
            for (Map.Entry<String, String> entry : parms.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                formBody.add(key, value);
            }
        }
        RequestBody body = formBody.build();
        builder.url(url).post(body).build();
        return builder;
    }

    @Override
    public Request.Builder builderPost(String url, String path, Map<String, String> parms) {
        Request.Builder builder = new Request.Builder();
        builder.addHeader("userCookieName", CacheUtil.getCache().getCookie());
        MediaType meta
                = MediaType.parse("text/x-markdown; charset=utf-8");
        MultipartBody.Builder mulBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File file = new File(path);
        if (file.exists()) {
            RequestBody body = RequestBody.create(meta, file);
            mulBody.addFormDataPart("file", file.getName(), body);
            mulBody.addFormDataPart("userId", CacheUtil.getCache().getUid());
            if (parms != null) {
                for (Map.Entry<String, String> entry : parms.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    mulBody.addFormDataPart(key, value);
                }
            }
            builder.url(url).post(mulBody.build()).build();
        }

        return builder;
    }
}
